#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPlainTextEdit>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("简单的记事本");

    //获取到菜单栏
    QMenuBar* menuBar = this->menuBar();
    //添加菜单
    QMenu* menu = new QMenu("文件");
    menuBar->addMenu(menu);
    //添加菜单项
    QAction* action1 = new QAction("打开");
    QAction* action2 = new QAction("保存");
    menu->addAction(action1);
    menu->addAction(action2);

    //指定一个输入框
    edit = new QPlainTextEdit();
    QFont font;
    font.setPixelSize(20);
    edit->setFont(font);
    this->setCentralWidget(edit);

    connect(action1, &QAction::triggered, this, &MainWindow::handleAction1);
    connect(action2, &QAction::triggered, this, &MainWindow::handleAction2);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleAction1()
{
    //先弹出打开文件对话框，让用户选择要打开的文件
    QString path = QFileDialog::getOpenFileName(this);
    //将文件名显示到状态栏中
    QStatusBar* statusBar = new QStatusBar();
    statusBar->showMessage(path);
    //根据用户选择的路径，构造一个 QFile 对象
    QFile file(path);
    bool ret = file.open(QIODevice::ReadOnly);
    if(!ret)
    {
        statusBar->showMessage(path + "打开失败！");
        return;
    }
    //读取文件
    QString text = file.readAll();
    //关闭文件
    file.close();
    //读到的内容显示到输入框中
    edit->setPlainText(text);

}

void MainWindow::handleAction2()
{
    //先弹出保存文件的对话框
    QString path = QFileDialog::getSaveFileName(this);
    //将文件名显示到状态栏中
    QStatusBar* statusBar = new QStatusBar();
    statusBar->showMessage(path);
    //根据用户选择的路径，构造一个 QFile 对象
    QFile file(path);
    bool ret = file.open(QIODevice::WriteOnly);
    if(!ret)
    {
        statusBar->showMessage(path + "打开失败！");
        return;
    }
    //写文件
    const QString& text = edit->toPlainText();
    file.write(text.toUtf8());

    //关闭文件
    file.close();
}






